package com.ikingtech.platform.service.system.role.service.repository;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ikingtech.framework.sdk.role.model.RoleDTO;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.system.role.entity.RoleDO;
import com.ikingtech.platform.service.system.role.entity.RoleDataScopeDO;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public class ModelConverter {

    private final RoleDataScopeRepository dataScopeService;

    public List<RoleDTO> modelConvert(List<RoleDO> entities) {
        if (Tools.Coll.isBlank(entities)) {
            return new ArrayList<>();
        }
        Map<String, List<String>> dataScopeMap = Tools.Coll.convertGroup(this.dataScopeService.list(Wrappers.<RoleDataScopeDO>lambdaQuery().in(RoleDataScopeDO::getRoleId, Tools.Coll.convertList(entities, RoleDO::getId))), RoleDataScopeDO::getRoleId, RoleDataScopeDO::getDataScopeCode);
        return Tools.Coll.convertList(entities, entity -> this.modelConvert(entity, dataScopeMap.get(entity.getId())));
    }

    public RoleDTO modelConvert(RoleDO entity, List<String> dataScopeCodes) {
        RoleDTO role = Tools.Bean.copy(entity, RoleDTO.class);
        role.setDataScopeCodes(dataScopeCodes);
        if (null != role.getDataScopeType()) {
            role.setDataScopeTypeName(role.getDataScopeType().description);
        }
        return role;
    }
}
